package com.gitee.huanminabc.jcommon.file.csv;

import com.gitee.huanminabc.jcommon.str.StringTypeCastUtil;
import com.gitee.huanminabc.jcommon.reflect.GenericUtil;
import com.gitee.huanminabc.jcommon.base.PatternUtil;
import lombok.SneakyThrows;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * csv转对象
 *
 * @Author: huanmin
 * @Date: 2022/6/18 15:59
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
public class CSVToObj<T>  {
    private String separator;  //默认分隔符
    private List<String> objects;//数据
    private List<T> list = new ArrayList<>();//数据
    private Map<Integer, Field> fields= new LinkedHashMap<>();

    public CSVToObj(List<String> objects, String separator) {
        //特殊符号的处理
        this.separator = PatternUtil.division(separator);
        this.objects = objects;
    }

    //列,映射,转换的时候会和映射的顺序保持一致 ,默认使用当前文件的分隔符作为切割
    public CSVToObj<T> mapping(String fieldNames) {
        String[] split = fieldNames.split(separator);
        Class<?> aClass = GenericUtil.getClassGenericType(getClass(), 0);
        Field[] declaredFields = aClass.getDeclaredFields();
        for (int i = 0; i < split.length; i++) {
            String s = split[i].trim();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                if (s.equals(declaredField.getName())) {
                    fields.put(i, declaredField);
                }
            }
        }

        return this;
    }

    @SneakyThrows
    public CSVToObj<T> transform() {
        Class<?> aClass = GenericUtil.getClassGenericType(getClass(), 0);
        for (String object : objects) {
            String[] split = object.split(separator);
            T o = (T) aClass.newInstance();
            fields.forEach((index, field) -> {
                field.setAccessible(true);
                try {
                    field.set(o, StringTypeCastUtil.cast(split[index], field.getType()));
                } catch (Exception e) {
                    throw new RuntimeException("字段转换失败: " + field.getName(), e);
                }
            });
            list.add(o);
        }
        return this;
    }

    public List<T> result() {
        return list;
    }


}
